// pages/my-posting-ZX/my-posting-ZX.js
const app = getApp();
const db = wx.cloud.database().collection("groupnews")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    value: '',
    imageList: [], 
    enable: false,
    loadingProps: {
      size: '50rpx',
    },
    filmName: '',
    imgUrl: '',
    isEditing: false,
    editId: null,
    oldImgUrl: '',
  },
  onLoad: function () {
    // 在页面加载时调用函数进行数据库查询
    this.getImageList();
  },
  showImage(e) {
    const datasetUrl = e.currentTarget.dataset.url;
    console.log("datasetUrl:", datasetUrl);
    // Ensure that the datasetUrl is not undefined or empty
    if (datasetUrl) {
      wx.navigateTo({
        url: '/pages/film-ZX-detail/film-ZX-detail?url=' + datasetUrl
      });
    } else {
      console.error("Image URL is undefined or empty.");
    }
  },
  getImageList: function () {
    db.where({
      _openid: app.globalData.user_openid,
      
    })
    .get().then(res => { 
      console.log(res.data)
      this.setData({
        imageList: res.data
      });
    }).catch(err => {
      console.error('Failed to get image list:', err);
    });
  }
  ,
  ready() {
    this.setData({ enable: true });
    setTimeout(() => {
      this.setData({ enable: false });
    }, 1000);
  },
  onRefresh() {
    this.setData({ enable: true });
    this.getImageList();
    setTimeout(() => {
      this.setData({ enable: false });
    }, 1500); 
  }
  ,
  onScroll(e) {
    const { scrollTop } = e.detail;
    this.setData({ scrollTop });
  },
  handleDelete(e) {
    const index = e.currentTarget.dataset.index;
    const item = this.data.imageList[index];
    const id = item._id;
    
    db.doc(id).remove()
      .then(() => {
        wx.showToast({ title: '删除成功', icon: 'none' });
        this.getImageList();
      })
      .catch(err => {
        wx.showToast({ title: '删除失败', icon: 'none' });
        console.error('Failed to delete item:', err);
      });
  },
  
  handleEdit(e) {
    const index = e.currentTarget.dataset.index;
    const item = this.data.imageList[index];
    const id = item._id;
    const title = item.title;
    const imageUrl = item.picture_url;
    this.setData({
      isEditing: true,
      editId: id,
      filmName: title,
      imgUrl: imageUrl,
      oldImgUrl: imageUrl  // 保存旧图片的fileID
    });
  },
  
  handleUpload() {
    let that = this;
    wx.chooseImage({
      success: chooseResult => {
        wx.showLoading({
          title: '上传中',
        });
        // 将图片上传至云存储空间
        wx.cloud.uploadFile({
          // 指定上传到的云路径
          cloudPath: 'groupnews/' + (new Date()).valueOf() + '.png',
          // 指定要上传的文件的小程序临时文件路径
          filePath: chooseResult.tempFilePaths[0],
          // 成功回调
          success: res => {
            console.log('上传成功', res);
            wx.hideLoading();
            wx.showToast({
              title: '上传图片成功',
            });
            if (res.fileID) {
              // 删除旧图片
              if (that.data.oldImgUrl) {
                wx.cloud.deleteFile({
                  fileList: [that.data.oldImgUrl],
                  success: deleteRes => {
                    console.log('旧图片删除成功', deleteRes);
                  },
                  fail: err => {
                    console.error('旧图片删除失败', err);
                  }
                });
              }
              that.setData({
                zhaopian: '图片如下',
                imgUrl: res.fileID
              });
            }
          },
          fail: err => {
            wx.hideLoading();
            console.error('上传失败', err);
            wx.showToast({
              title: '上传失败，请重试',
              icon: 'none'
            });
          }
        });
      },
      fail: err => {
        console.error('选择图片失败', err);
        wx.showToast({
          title: '选择图片失败，请重试',
          icon: 'none'
        });
      }
    });
  },
  

  publishGroupNews() {
    const { editId, filmName, imgUrl } = this.data;
    if (!filmName || !imgUrl) {
      wx.showToast({
        title: '请输入片名并上传海报',
        icon: 'error'
      });
      return;
    }
  
    // 更新数据库的逻辑
    db.doc(editId).update({
      data: {
        title: filmName,
        picture_url: imgUrl,
      }
    }).then(() => {
      wx.showToast({ title: '修改成功', icon: 'none' });
      this.setData({
        isEditing: false,
        editId: null,
        filmName: '',
        imgUrl: '',
        oldImgUrl: ''  // 清空旧图片的fileID
      });
      this.getImageList();
    }).catch(err => {
      wx.showToast({ title: '修改失败，请重试', icon: 'none' });
      console.error('修改失败:', err);
    });
  },
  
  cancelEdit() {
    this.setData({
      isEditing: false,
      editId: null,
      filmName: '',
      imgUrl: '',
    });
  },
})